package com.bookbuf.qq;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.bookbuf.qq.content.QQShareContent;
import com.bookbuf.qq.content.QQShareType;
import com.bookbuf.qq.localize.QQPreferences;
import com.bookbuf.social.PlatformEnum;
import com.bookbuf.social.handlers.SSOHandler;
import com.bookbuf.social.platforms.QQPlatform;
import com.bookbuf.social.share.content.ShareContent;
import com.bookbuf.social.share.content.media.image.ImageMedia;
import com.bookbuf.social.share.content.media.image.util.BitmapUtils;
import com.bookbuf.social.util.QueuedWork;
import com.tencent.connect.UserInfo;
import com.tencent.connect.share.QQShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * author: robert.
 * date :  16/8/12.
 */
public class QQSsoHandler extends TencentSSOHandler<QQPlatform> {
	private Activity mActivity;
	private static final String TAG = "QQSsoHandler";
	private IUiListener mShareListener;
	private QQShareContent mShareContent;
	private Bundle mParams;
	private QQPreferences qqPreferences;

	public QQSsoHandler () {
	}

	@Override
	public void onCreate (Context context, QQPlatform p) {
		super.onCreate (context, p);
		if (context != null) {
			this.qqPreferences = new QQPreferences (context, PlatformEnum.QQ.toString ());
		}

	}

	@Override
	public boolean share (Activity activity, ShareContent content, SSOHandler.ShareListener listener) {
		if (activity == null) {
			return false;
		} else {
			this.mParams = null;
			this.mActivity = activity;
			this.mShareListener = this.getShareListener (listener);
			if (this.mShareListener == null) {
				Log.w (TAG, "share: mShareListener null.");
			}

			this.mShareContent = new QQShareContent.WXShareContentWrapper (content).build ();
			this.shareToQQ (activity);
			return false;
		}
	}

	private IUiListener getShareListener (final SSOHandler.ShareListener listener) {
		return new IUiListener () {
			public void onError (UiError e) {
				if (e != null) {
				}

				listener.onError (PlatformEnum.QQ, (Throwable) null);
			}

			public void onCancel () {
				listener.onCancel (PlatformEnum.QQ);
			}

			public void onComplete (Object response) {
				listener.onResult (PlatformEnum.QQ);
			}
		};
	}

	@Override
	public boolean isAuthorized (Context mContext) {
		return mContext != null && this.qqPreferences != null ? this.qqPreferences.isAuthValid () : false;
	}

	@Override
	public void applyAuthorize (Activity act, SSOHandler.AuthListener listener) {
		if (act == null) {
			Log.d ("UMError", "qq authorize activity is null");
		} else {
			this.mActivity = act;
			this.authListener = listener;
			this.loginDeal ();
		}
	}

	private IUiListener getAuthListener (final SSOHandler.AuthListener listener) {
		return new IUiListener () {
			public void onError (UiError e) {
				if (e != null) {
					Log.d (TAG, "授权失败! ==> errorCode = " + e.errorCode + ", errorMsg = " + e.errorMessage + ", detail = " + e.errorDetail);
				}

				listener.onError (PlatformEnum.QQ, 0, new Throwable ("授权失败! ==> errorCode = " + e.errorCode + ", errorMsg = " + e.errorMessage + ", detail = " + e.errorDetail));
			}

			public void onCancel () {
				if (listener != null) {
					listener.onCancel (PlatformEnum.QQ, 0);
				}

			}

			public void onComplete (Object response) {
				Bundle values = QQSsoHandler.this.parseOauthData (response);
				if (QQSsoHandler.this.qqPreferences == null && QQSsoHandler.this.mActivity != null) {
					QQSsoHandler.this.qqPreferences = new QQPreferences (QQSsoHandler.this.mActivity, PlatformEnum.QQ.toString ());
				}

				if (QQSsoHandler.this.qqPreferences != null) {
					QQSsoHandler.this.qqPreferences.setAuthData (values).commit ();
				}

				QQSsoHandler.this.initOpenidAndToken ((JSONObject) response);
				if (listener != null) {
					listener.onComplete (PlatformEnum.QQ, 0, QQSsoHandler.this.bundleTomap (values));
				}

				if (values != null) {
					int status = Integer.valueOf (values.getString ("ret")).intValue ();
					if (status == 0) {
						return;
					}
				}

			}
		};
	}


	@Override
	public void deleteAuthorize (Context context, SSOHandler.AuthListener listener) {
		this.tencent.logout (context);
		if (this.qqPreferences != null) {
			this.qqPreferences.delete ();
		}
		listener.onComplete (PlatformEnum.QQ, 1, (Map) null);
	}

	private void loginDeal () {
		Log.i (TAG, "QQ oauth login...");
		if (this.isInstalled (this.mActivity)) {
			Log.d ("qq", "installed qq");
			this.tencent.login (this.mActivity, "all", this.getAuthListener (this.authListener));
		} else {
			Log.d ("qq", "didn\'t install qq");
			this.tencent.loginServerSide (this.mActivity, "all", this.getAuthListener (this.authListener));
		}

	}

	public void initOpenidAndToken (JSONObject jsonObject) {
		try {
			String token = jsonObject.getString ("access_token");
			String expires = jsonObject.getString ("expires_in");
			String openId = jsonObject.getString ("openid");
			if (!TextUtils.isEmpty (token) && !TextUtils.isEmpty (expires) && !TextUtils.isEmpty (openId)) {
				this.tencent.setAccessToken (token, expires);
				this.tencent.setOpenId (openId);
			}
		} catch (Exception var5) {
			var5.printStackTrace ();
		}

	}

	private Map<String, String> bundleTomap (Bundle bundle) {
		if (bundle != null && !bundle.isEmpty ()) {
			Set keys = bundle.keySet ();
			HashMap map = new HashMap ();
			Iterator var4 = keys.iterator ();

			while (var4.hasNext ()) {
				String key = (String) var4.next ();
				map.put (key, bundle.getString (key));
			}

			return map;
		} else {
			return null;
		}
	}

	public void shareToQQ (Context context) {
		if (this.isTencentInfoValid ()) {
			String path = (String) this.mShareContent.mExtraData.get (Constant.IMAGE_PATH_LOCAL);
			if (this.isLoadImageAsync (context)) {
				String image1 = (String) this.mShareContent.mExtraData.get (Constant.IMAGE_PATH_URL);
				this.loadImage (image1);
				return;
			}

			if (this.isUploadImageAsync (path, this.mShareContent.getType ().getCode (), context)) {
				ImageMedia image = new ImageMedia (new WeakReference<Context> (context), new File (path));
				Log.w (TAG, "未安装QQ客户端的情况下，QQ不支持音频，图文是为本地图片的分享。此时将上传本地图片到相册，请确保在QQ互联申请了upload_pic权限.");
				SSOHandler.AuthListener authListener = this.createUploadAuthListener (image);
				this.applyAuthorize (this.mActivity, authListener);
				return;
			}

			Log.d ("shareQQ", "share to qq");
			this.defaultShareToQQ (this.mShareContent);
		} else {
			Log.d (TAG, "QQ平台还没有授权");
			this.applyAuthorize (this.mActivity, (SSOHandler.AuthListener) null);
		}

	}

	private SSOHandler.AuthListener createUploadAuthListener (final ImageMedia image) {
		return new SSOHandler.AuthListener () {
			public void onComplete (PlatformEnum platform, int action, Map<String, String> data) {
				if (data != null && data.containsKey ("uid") && !TextUtils.isEmpty (image.asUrlImage ())) {
					QQSsoHandler.this.mParams.putString (QQShare.SHARE_TO_QQ_IMAGE_URL, image.asUrlImage ());
					QQSsoHandler.this.mParams.remove (QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL);
					QQSsoHandler.this.defaultShareToQQ (QQSsoHandler.this.mShareContent);
				}

			}

			public void onError (PlatformEnum platform, int action, Throwable t) {
			}

			public void onCancel (PlatformEnum platform, int action) {
			}
		};
	}

	protected boolean isUploadImageAsync (String imagePath, int type, Context context) {
		if (TextUtils.isEmpty (imagePath)) {
			return false;
		} else {
			PlatformEnum platform = this.platform.getName ();
			boolean hasClient = this.isInstalled (context);
			boolean isLocalImage = !imagePath.startsWith ("http://") && !imagePath.startsWith ("https://");
			if (!hasClient && isLocalImage) {
				if (platform == PlatformEnum.QQ && (type == QQShareType.IMAGE.getCode () || type == QQShareType.TEXT_PLUS_IMAGE.getCode ())) {
					return true;
				}
			}
			return false;
		}
	}

	private boolean isLoadImageAsync (Context context) {
		String urlPath = (String) this.mShareContent.mExtraData.get (Constant.IMAGE_PATH_URL);
		String localPath = (String) this.mShareContent.mExtraData.get (Constant.IMAGE_PATH_LOCAL);
		return this.mShareContent.getType ().getCode () == QQShare.SHARE_TO_QQ_TYPE_AUDIO
				&& this.isInstalled (context) && !TextUtils.isEmpty (urlPath) && TextUtils.isEmpty (localPath);
	}

	private void loadImage (String imageUrlPath) {
		BitmapUtils.getBitmapFromFile (imageUrlPath);
		String localPath = BitmapUtils.getFileName (imageUrlPath);
		this.mParams.putString (QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
		this.mParams.remove (QQShare.SHARE_TO_QQ_IMAGE_URL);
		this.defaultShareToQQ (this.mShareContent);
	}

	private void defaultShareToQQ (QQShareContent shareContent) {
		this.mParams = shareContent.build ();
		this.mParams.putString (QQShare.SHARE_TO_QQ_APP_NAME, this.getAppName ());
		if (this.mParams != null) {
			QueuedWork.runInMain (new Runnable () {
				public void run () {
					QQSsoHandler.this.tencent.shareToQQ (QQSsoHandler.this.mActivity, QQSsoHandler.this.mParams, QQSsoHandler.this.mShareListener);
					Log.i (TAG, "run: " + QQSsoHandler.this.mParams.toString ());
				}
			});
		}

	}

	public static final int INTENT_REQUEST_CODE_SHARE = 10103;
	public static final int INTENT_REQUEST_CODE_AUTH = 11101;

	@Override
	public int getRequestCode () {
		return INTENT_REQUEST_CODE_SHARE;
	}

	@Override
	public void onActivityResult (int requestCode, int resultCode, Intent data) {
		if (requestCode == INTENT_REQUEST_CODE_SHARE) {
			Tencent.onActivityResultData (requestCode, resultCode, data, this.mShareListener);
		}
		if (requestCode == INTENT_REQUEST_CODE_AUTH) {
			Tencent.onActivityResultData (requestCode, resultCode, data, this.getAuthListener (this.authListener));
		}

	}

	@Override
	public void callApiProfile (Activity act, final AuthListener listener) {
		if (this.isAuthorized (act)) {
			try {
				String userInfo = this.qqPreferences.getmAccessToken ();
				String expires = QQPreferences.getExpiresIn ();
				String openId = this.qqPreferences.getmUID ();
				if (act != null && this.qqPreferences != null) {
					userInfo = this.qqPreferences.getmAccessToken ();
					expires = QQPreferences.getExpiresIn ();
					openId = this.qqPreferences.getmUID ();
				}

				if (!TextUtils.isEmpty (userInfo) && !TextUtils.isEmpty (expires) && !TextUtils.isEmpty (openId)) {
					this.tencent.setAccessToken (userInfo, expires);
					this.tencent.setOpenId (openId);
				}
			} catch (Exception var6) {
				var6.printStackTrace ();
			}
		}

		if (act == null) {
			Log.d ("UMError", "QQ getPlatFormInfo activity is null");
		} else {
			UserInfo userInfo = new UserInfo (act, this.tencent.getQQToken ());
			userInfo.getUserInfo (new IUiListener () {
				public void onCancel () {
				}

				public void onComplete (Object arg) {
					try {
						JSONObject e = new JSONObject (arg.toString ());
						HashMap infos = new HashMap ();
						infos.put ("screen_name", e.optString ("nickname"));
						infos.put ("gender", e.optString ("gender"));
						infos.put ("profile_image_url", e.optString ("figureurl_qq_2"));
						infos.put ("is_yellow_year_vip", e.optString ("is_yellow_year_vip"));
						infos.put ("yellow_vip_level", e.optString ("yellow_vip_level"));
						infos.put ("msg", e.optString ("msg"));
						infos.put ("city", e.optString ("city"));
						infos.put ("vip", e.optString ("vip"));
						infos.put ("level", e.optString ("level"));
						infos.put ("province", e.optString ("province"));
						infos.put ("is_yellow_vip", e.optString ("is_yellow_vip"));
						if (QQSsoHandler.this.qqPreferences != null) {
							infos.put ("openid", QQSsoHandler.this.qqPreferences.getuid ());
						}

						listener.onComplete (PlatformEnum.QQ, AuthListener.ACTION_GET_PROFILE, infos);
					} catch (JSONException var4) {
						listener.onComplete (PlatformEnum.QQ, AuthListener.ACTION_GET_PROFILE, (Map) null);
					}

				}

				public void onError (UiError arg0) {
					listener.onError (PlatformEnum.QQ, AuthListener.ACTION_GET_PROFILE, new Throwable (arg0.toString ()));
				}
			});
		}
	}

	@Override
	public void callApiCheckAccessTokenValid (Activity activity, AuthListener listener) {
		applyAuthorize (activity, listener);
	}
}